package SeqList;

public class SeqList<T> implements ISeqList<T> {
    Object[] element;
    int len;

    public SeqList(int size){
        this.element = new Object[size];
        this.len = 0;
    }

    @Override
    public boolean isEmpty() {
        return this.len == 0;
    }

    @Override
    public int length() {
        return this.len;
    }

    @Override
    public Object get(int i) {
        return this.element[i];
    }

    @Override
    public void set(int i, T x) {
        if (x == null){//对象不能设置为空
            return;
        }
        if(i >= 0 && i < this.len){
            this.element[i] = x;
        }else{
            throw new IndexOutOfBoundsException(i + "");
        }
    }

    @Override
    public void insert(int i, T x) {
        if(element[i] == null){//阻止插入空值
            return;
        }
        if(i < 0){//阻止插入到错误下标的值
            i = 0;
        }
        if (this.len == element.length){//满串扩容
            Object[] temp = this.element;
            this.element = new Object[temp.length + 1];
            for(int j = 0;j < temp.length; j++){
                this.element[j] = temp[j];
            }
        }
        for(int j = this.len - 1;j >= i;j--){
            this.element[j + 1] = this.element[j];
        }
        element[i] = x;
        this.len++;
    }

    @Override
    public void lengthen(T x) {
        insert(this.len , x);
    }

    @Override
    public T remove(int i) {
        if(this.len == 0 || i < 0 || i >= this.len){
            System.out.println("delete position=" + i + ",is out index.");
            return null;
        }
        T deleted = (T) this.element[i];
        System.out.println("node:" + deleted + ",is deleted from seqlist.");
        for(int j = i; j < this.len - 1; j++){//把i后的数据元素依次前移
            this.element[j] = this.element[j + 1];
        }
        this.element[this.len - 1] = null;
        this.len--;
        return deleted;
    }

    @Override
    public void removeAll() {//删除线性表内所有值
        this.len = 0;
    }

    @Override
    public int search(T key) {
        for(int i = 0; i < this.len; i++){
            if(key.equals(this.element[i])){//搜寻地址与key相同的元素
                return i;
            }
        }
        return -1;
    }

    @Override
    public T[] getElements() {
        return (T[]) this.element;
    }
}
